package com.fowo.api.syncAmazon.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fowo.api.datainterface.service.DatainterfaceService;
import com.fowo.api.entity.AmzAdvertisAuthInfo;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

/**
 * @fileName: AbstractAdSyncData
 * @Description: 代码目的，作用，如何工作
 * @Author: yyf
 * @Date: 2024/4/29 0029 16:10
 */
public abstract class AbstractAmzAdSyncData extends AbstractAmazonSyncData{
    @Resource
    private DatainterfaceService datainterfaceService;
    @Resource
    protected AmazonAdvertAuthAction amazonAdvertAuthAction;
    private String validToken;
    private String refreshToken;
    private long tokenExpirationTime = 0L;
    protected static final String TIME_UNIT = "DAILY";
    protected static final String FORMAT = "GZIP_JSON";
    private String contentType = "application/vnd.createasyncreportrequest.v3+json";
    private void setToken(String refreshToken){
        JSONObject tokenInfo = amazonAdvertAuthAction.getTokenInfo(refreshToken);
        this.validToken = tokenInfo.getString("access_token");
        Long expiresIn = tokenInfo.getLong("expires_in");
        this.refreshToken = tokenInfo.getString("refresh_token");
        this.tokenExpirationTime = System.currentTimeMillis()+expiresIn*1000;
    }

    protected String getToken(String refreshToken){
        if(!refreshToken.equals(this.refreshToken)){
            setToken(refreshToken);
        }else if(System.currentTimeMillis() >= tokenExpirationTime){
            setToken(refreshToken);
        }
        return this.validToken;
    }
    /**
     * 创建亚马逊广告报告
     */
    protected String createReport(Object params,Object headers) {
        logger.info("创建报告中");
        Object res = datainterfaceService.executeInterface(null, "EC00567", null, params, headers);
        JSONObject response = JSONObject.parseObject(res.toString());
        String reportId = response.getString("reportId");
        return reportId;
    }

    /**
     * 检查检查亚马逊广告报告状态
     * @param reportId 报告id
     * @param headers 请求头信息
     * @return
     * @throws Exception
     */
    protected String checkReport(String reportId, Object headers) throws Exception {
        logger.info("检查报告中");
        //等待60S再请求
        Thread.currentThread().sleep(60000);

        Map<String,Object> param = new HashMap<>();
        param.put("path",reportId);
        Object res = datainterfaceService.executeInterface(null, "EC00569", null, param, headers);
        JSONObject response = JSONObject.parseObject(res.toString());
        String reportStatus = response.getString("status");

        switch (reportStatus){
            case "PROCESSING":
            case "PENDING":
                return checkReport(reportId,headers);
            case "COMPLETED":
                return response.get("url").toString();
            default:
                throw new Exception("商品报告状态异常");
        }
    }

    protected JSONArray getAndUnzipReport(String url) throws IOException {
        logger.info("正在下载GZIP文件");
        // 使用OkHttp下载GZIP文件
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }

        // 通过GZIPInputStream解压
        InputStream gzipInputStream = new GZIPInputStream(response.body().byteStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = gzipInputStream.read(buffer)) > 0) {
            baos.write(buffer, 0, length);
        }
        gzipInputStream.close();
        response.body().close();

        // 获取解压后的JSON字符串
        String jsonString = baos.toString(StandardCharsets.UTF_8);

        // 使用Fastjson解析JSON
        JSONArray res = JSON.parseArray(jsonString);
        return res;
    }
    protected Map<String,Object> getHeaders(AmzAdvertisAuthInfo amzAdvertisAuthInfo){
        logger.info("正在获取请求头");
        Map<String,Object> headers = new HashMap<>(4);
        headers.put("Content-type",contentType);
        headers.put("Amazon-Advertising-API-ClientId",AmazonAdvertAuthAction.CLIENT_ID);
        headers.put("Amazon-Advertising-API-Scope",amzAdvertisAuthInfo.getProfileId());
        headers.put("Authorization","Bearer "+getToken(amzAdvertisAuthInfo.getRefreshToken()));
        return headers;
    }
}
